package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.constants.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior>
        implements ApReadBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    KafkaTemplate kafkaTemplate;

    /**
     * 保存阅读行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //查询行为实体
        ApBehaviorEntry behaviorEntry = null;
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {//设备登录
            behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null, 0);
        }

        if (user != null && user.getId() != null) {
            behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), null);
        }

        if (behaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        ApReadBehavior readBehavior = getOne(Wrappers.<ApReadBehavior>lambdaQuery()
                .eq(ApReadBehavior::getEntryId, behaviorEntry.getId())
                .eq(ApReadBehavior::getArticleId, dto.getArticleId())
        );


        //保存或者更新文章阅读行为
        if (readBehavior == null) {//保存文章
            readBehavior = new ApReadBehavior();
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setCreatedTime(new Date());
            readBehavior.setCount(dto.getCount());
            readBehavior.setEntryId(behaviorEntry.getId());
            readBehavior.setLoadDuration(dto.getLoadDuration());
            readBehavior.setPercentage(dto.getPercentage());
            readBehavior.setReadDuration(dto.getReadDuration());
            save(readBehavior);

        } else {//更新文章
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setCount((short) (dto.getCount()+1));
            readBehavior.setPercentage(dto.getPercentage());
            readBehavior.setEntryId(behaviorEntry.getId());
            readBehavior.setLoadDuration(dto.getLoadDuration());

            updateById(readBehavior);
        }

        //**** 文章阅读-发送消息
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setArticleId(dto.getArticleId());
        kafkaTemplate.send(HotArticleConstants.HOTARTICLE_SCORE_INPUT_TOPIC,
                UUID.randomUUID().toString(), JSON.toJSONString(mess));


        //返回结果

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
